var express = require('express');
var router = express.Router();
var fileDetails = require('../models/fileDetails');
//file API

router.use(function(req, res, next) {
    console.log('Something is happening.');
    next();
});

router.get('/', function(req, res) {
    res.json({ message: 'hooray! welcome to our api!' });
});

router.route('/file')
    .get(function(req, res) {
        fileDetails.find(function(err, files) {
            if (err) {
                res.send(err);
            }
            res.json({
                message: 'success!',
                files: files
            });
        });
    })
    .post(function(req, res) {
        console.log(req.body);
        var file = new fileDetails();
        file.name = req.body.name;
        file.size = req.body.size;
        file.type = req.body.type;
        file.save(function(err, data) {
            if (err)
                res.send(err);
            res.json({
                message: 'file created!',
                data: data
            });
        });
    });

router.route('/file/:fileId').get(function(req, res) {
    fileDetails.findById(req.params.fileId, function(err, file) {
        if (err)
            res.send(err);
        res.json({
            message: 'success!',
            file: file
        });
    });
}).put(function(req, res) {
    fileDetails.findById(req.params.fileId, function(err, file) {
        if (err)
            res.send(err);
        file.name = req.body.name;

        file.save(function(err, data) {
            if (err)
                res.send(err);
            res.json({
                message: 'File updated!',
                data: data
            });
        });

    });
}).delete(function(req, res) {
    fileDetails.findByIdAndRemove(req.params.fileId, function(err, data) {
        if (err)
            res.send(err);
        res.json({
            message: 'File delete!',
            data: data
        });
    })
});

module.exports = router;